package com.etoak.common.web.handler;

import com.etoak.common.core.vo.ResultVO;
import com.etoak.common.web.exception.CustomException;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.xml.transform.Result;
import java.util.stream.Collectors;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler
//    @ResponseStatus()
    public ResultVO<Object> handler(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        String collect = e.getAllErrors().stream().map(ObjectError::getDefaultMessage).
                collect(Collectors.joining(";"));
        return ResultVO.failed(collect);
    }

    /*
    * 处理 校验规则放在接口参数中的校验
    * */
    @ExceptionHandler
    public ResultVO<Object> handler(ConstraintViolationException e){
        log.error(e.getMessage(),e);
        String collect = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage)
                .collect(Collectors.joining(";"));
        return ResultVO.failed(collect);
    }

    @ExceptionHandler
    public ResultVO<Object> handler(CustomException e){
        log.error(e.getMessage(),e);
        String message = e.getMessage();
        return ResultVO.failed(message);
    }


    @ExceptionHandler
    public ResultVO<Object> handler(Exception e){

        log.error(e.getMessage(),e);
        return ResultVO.failed();
    }
}
